package com.tbit.uqbike.webmanager.util.csv.aspect;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.tbit.uqbike.object.pojo.DownloadHistory;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.base.TokenService;
import com.tbit.uqbike.webmanager.dao.capital.DownloadHistoryDao;
import com.tbit.uqbike.webmanager.util.csv.annotations.AsyncDownload;
import com.tbit.uqbike.webmanager.util.csv.config.CsvExportConfig;
import com.tbit.uqbike.webmanager.util.csv.entity.DownloadDTO;
import com.tbit.uqbike.webmanager.util.csv.entity.MethodInfo;
import com.tbit.uqbike.webmanager.util.csv.util.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author wei.xing
 * @date 2021/3/2514:18
 * @Description:
 */
@Aspect
@Component
@Slf4j
public class ExportAspect {

    @Autowired
    DownloadHistoryDao historyDao;
    @Autowired
    CsvExportConfig config;
    @Autowired
    private TokenService tokenService;

    @Pointcut("@annotation(com.tbit.uqbike.webmanager.util.csv.annotations.AsyncDownload)")
    private void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        try {
            Object[] args = joinPoint.getArgs();

            if (args.length == 0 || !(args[0] instanceof DownloadDTO)) {
                throw new RuntimeException("参数不合法,必须传递DownloadDTO");
            }
            DownloadDTO downloadDTO = (DownloadDTO) args[0];
            //设置的文件名字
            Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
            AsyncDownload asyncDownload = method.getAnnotation(AsyncDownload.class);
            if (StrUtil.isBlank(downloadDTO.getFileName())) {
                if (downloadDTO.getStartTime() != null && downloadDTO.getEndTime() != null) {
                    downloadDTO.setFileName(
                            asyncDownload.defaultFileName() + "-" + DateUtil.formatDate(downloadDTO.getStartTime())
                                    + "-" + DateUtil.formatDate(downloadDTO.getEndTime()));
                } else {
                    downloadDTO.setFileName(
                            asyncDownload.defaultFileName() + "-" + DateUtil.formatDate(new Date()));
                }

            }
            //启动开关
            if (!config.getEnable()) {
                return joinPoint.proceed(joinPoint.getArgs());
            }

            //异步下载，记录任务信息，保存入库
            if (downloadDTO.getIsAsync() == null || downloadDTO.getIsAsync() == 2) {

                downloadDTO.setIsAsync(1);
                //记录方法信息
                String methodName = method.getName();
                String className = joinPoint.getTarget().getClass().getName();


                MethodInfo methodInfo = new MethodInfo();
                methodInfo.setArgs(args);
                methodInfo.setClassName(className);
                methodInfo.setMethodName(methodName);

                //记录下载任务
                DownloadHistory downloadHistory = new DownloadHistory();
                downloadHistory.setStatus(1);
                downloadHistory.setDelFlag(0);
                downloadHistory.setCreateTime(new Date());
                downloadHistory.setUpdateTime(new Date());

                //设置表记录的文件名字
                downloadHistory.setFileName(downloadDTO.getFileName());


                if (RequestContextHolder.getRequestAttributes() != null) {
                    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                    methodInfo.setUrl(request.getRequestURI());
                    LoginInfo loginInfo = tokenService.getLoginInfo();
                    downloadHistory.setOperatorId(loginInfo.getAccountUserId());
                    downloadHistory.setOperatorName(loginInfo.getName());
                    downloadHistory.setOperatorPhone(loginInfo.getPhone());
                }
                //设置表记录的过期时间
                if (downloadDTO.getExpire() != null) {
                    downloadHistory.setExpireTime(new Date(System.currentTimeMillis() + downloadDTO.getExpire()));
                } else {
                    downloadHistory.setExpireTime(new Date(System.currentTimeMillis() + config.getOssExpire()));
                }

                downloadHistory.setMethodInfo(JacksonUtil.toStr(methodInfo));
                historyDao.insert(downloadHistory);
                return Result.success();
            } else {
                return joinPoint.proceed(joinPoint.getArgs());
            }
        } catch (Throwable e) {
            log.error("目标方法执行异常,目标类:" + joinPoint.getTarget() + "方法：" + joinPoint.getSignature().getName());
            throw new RuntimeException(e);
        }
    }


}
